<template>

    <div class="todo-container">
      <div class="todo-wrap">
        <!--<todo-header :addTodos="addTodos" />-->
        <!--<todo-header @addTodosEmit="addTodos" />-->
        <todo-header ref="header"/>
        <!--<todo-list :todos="todos" :deleteTodos="deleteTodos"/>-->
        <todo-list :todos="todos" />
        <!--<todo-footer :selectAll="selectAll" :deleteCompleteTodos="deleteCompleteTodos"  :todos="todos"/>-->
        <todo-footer>
          <input type="checkbox" v-model="isCheck" slot="F1" />
          <span slot="F2">已完成{{todoSize}}/ 全部{{todos.length}}</span>
          <button class="btn btn-danger" v-show="todoSize" @click="deleteCompleteTodos" slot="F3">清除已完成任务</button>
        </todo-footer>
      </div>
    </div>

</template>

<script>
import TodoHeader from './components/TodoHeader'
import TodoList   from './components/TodoList'
import TodoFooter from './components/TodoFooter'
import PubSub     from 'pubsub-js'
export default {
  name: 'App',
  data(){
    return {
      /*todos:[
        {title:'吃饭',complete:false},
        {title:'睡觉',complete:true},
        {title:'打豆豆',complete:false}
      ]*/
      //从localStorage读取todos
      todos:JSON.parse(window.localStorage.getItem('todos_key') || '[] ')
    }
  },
  computed:{
    todoSize(){
      return this.todos.reduce( (pretotal,todo) => pretotal + (todo.complete ? 1 : 0 ),0)
    },
    isCheck:{
      get(){
        return this.todoSize === this.todos.length  && this.todoSize > 0
      },
      set(value){
        this.selectAll(value)
      }
    }
  },
  methods:{
    addTodos(todo){
      this.todos.unshift(todo)
    },
    deleteTodos(index){
      this.todos.splice(index,1)
    },
    selectAll(check){
      this.todos.forEach((todo) => todo.complete = check)
    },
    deleteCompleteTodos(){
      this.todos = this.todos.filter((todo) => !todo.complete)
    }
  },
  mounted(){
    this.$refs.header.$on('addTodosEmit',this.addTodos)
    //PubSub.subscribe(触发事件名,回调函数(事件名本身,数据))
    PubSub.subscribe('deleteTodosEmit',(msg,index) => {
      this.deleteTodos(index)
    })
  },
  watch:{
    todos:{
      deep:true,//深度监视
      handler:function (value) {
        //将todos最新的值,保存到localstorage
        window.localStorage.setItem('todos_key',JSON.stringify(value))
      }
    }
  },
  components: {
    TodoList,
    TodoHeader,
    TodoFooter
  }
}
</script>

<style>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }

</style>
